/**
 * @author Melinda
 */

var map;
var geocoder;
var markerArray = [];
var latlngbounds; 

function court(id, lat, long, bball, vball, field, diamond) {
	this.id = id;
	this.lat = lat;
	this.long = long;
	this.bball = bball;
	this.vball = vball;
	this.field = field;
	this.diamond = diamond;
	this.count = 0;
}
function initialize() {
	geocoder = new google.maps.Geocoder();
	latlngbounds= new google.maps.LatLngBounds();
	var latlng = new google.maps.LatLng(42.353, -71.067);
	var myOptions = {
		zoom : 8,
		center : latlng,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
processFilter();
//map.fitBounds(latlngbounds);
	// setMarkers(map, locations);
	// To add the marker to the map, call setMap();
	// marker.setMap(map);
}

var locations = [
// [name, lat, long, bball, field, diamond]
[ 'Boston Commons', 42.353, -71.067, 1, 1, 1 ],
		[ 'Almont Playground', 42.274543, -71.0972735, 1, 1, 0 ]

];

function processFilter(box) {
	var bballCheck = $('#bballRadio').attr('checked');
	var baseCheck = $('#baseballRadio').attr('checked');
	var fieldCheck = $('#fieldRadio').attr('checked');
	var fieldInt, baseInt, ballInt;
	if (fieldCheck == true)
		fieldInt = "1";
	if (fieldCheck == false)
		fieldInt = "*";
	if (bballCheck == true)
		ballInt = "1";
	if (bballCheck == false)
		ballInt = "*";
	if (baseCheck == true)
		baseInt = "1";
	if (baseCheck == false)
		baseInt = "*";
	clearMarkers(map);
	//alert(fieldInt + ', ' + baseInt + ',' + ballInt);
	findField(fieldInt, baseInt, ballInt);
	
//	if(markerArray){
//		for(var i=0; i<markerArray.length; i++){
//		latlngbounds.extend( markerArray[i].getPosition() );
//		}
//		map.fitBounds(latlngbounds);
//	}
	// alert(box.value);
}
function findField(fHasOpenField, fHasDiamond, fHasBball) {
	$.post("backend.php", {
		f_id : "*",
		f_name : "*",
		f_long : "*",
		f_lat : "*",
		f_hasopenfield : fHasOpenField,
		f_hasdiamond : fHasDiamond,
		f_hasbball : fHasBball,
		post_action : "field_find"
	}, function(data) {
		 //alert(data);
		var JSONoutput = jQuery.parseJSON(data);
		// output = JSONoutput;
		var fieldList = JSONoutput.output;
		var field = [];
		var games = [];
		for (i = 0; i < fieldList.length; i++) {
			field = [ fieldList[i].f_id, fieldList[i].f_name,
					fieldList[i].f_lat, fieldList[i].f_long,
					fieldList[i].f_hasbball, fieldList[i].f_hasopenfield,
					fieldList[i].f_hasdiamond ];

			// alert(field);
			gamesList = fieldList[i].events;
			// alert(gamesList.length);
			// for (j = 0; j < gamesList.length; j++) {
			// games = [gamesList[i].e_id, gamesList[i].e_sport];
			// //alert(games);
			// }
			setMarker(map, field, gamesList);
		}
		// alert (output[0].f_id);
	});
	// return fields;
}
function getEventData(eid) {
	temp = $.post("backend.php", {
		e_id: eid,
		f_id: "*",
		e_sport: "*",
		e_timestart: "*",
		e_numppl: "*",
		e_equipment: "*",
		e_skill: "*",
		post_action: "event_find"
		}, function(data){
			//alert(data);
			var JSONoutput = jQuery.parseJSON(data);
			var eventData = JSONoutput.output;
			//alert(eventData);
			getEventDetails(eventData);
		});
}

function createSportEvent() {
	var fid = document.getElementById("content").title;
	var esport = document.getElementById("sport").value;
	
	var date = new Date();
	var month = parseInt(date.getMonth()) + 1;
	var time = date.getFullYear()+"-"+month.toString() +"-"+date.getDate() + " "+ date.getHours()+":"+date.getMinutes() +":"+date.getSeconds();
	var eduration = document.getElementById("duration").value;
	
	var enumppl = "1";
	var eequipment = document.getElementById("checkbox").value;
	if (eequipment == "on") {
		eequipment = "1";
	}
	else{
			eequipment = "1";
	}
	var eskill = document.getElementById("skill").value;
		
	//alert(fid + ',' + esport + ',' + eskill + ',' + eduration + ',' + eequipment);
	
	
	$.post("backend.php", {
		f_id: fid,
		e_sport: esport,
		e_timestart: time,
		e_duration: eduration,
		e_numppl: enumppl,
		e_equipment: eequipment,
		e_skill: eskill,
		post_action: "event_create"
		}, function(data){
			data = jQuery.parseJSON(data);
			if (data.output == "") create = false;
			else create = true;
		});
	alert('Event creation successful!');
	initialize();
	return create;
}


function joinEvent(eid, enumppl, eequipment) {
	temp = $.post("backend.php", {
		e_id: eid,
		e_numppl: enumppl,
		e_equipment: eequipment,
		post_action: "event_checkin"
		}, function(data){
			//alert(data);
			return data;
		});
}
function codeAddress() {
	var address = document.getElementById("address").value;
	geocoder.geocode({
		'address' : address
	}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			var marker = new google.maps.Marker({
				map : map,
				position : results[0].geometry.location
			});
			var infoWindow = new google.maps.InfoWindow();
			infoWindow.setContent(address);
			infoWindow.open(map, marker);	

			var latlngbounds = new google.maps.LatLngBounds();
			latlngbounds.extend(marker.position);
			map.setZoom(14);
		} else {
			alert("Geocode was not successful for the following reason: "
					+ status);
		}
	});
}
function getCapability(loc) {
	var text = '';
	if (loc[4] == '1') {
		text += '<img class="iconClass" title="Basketball Court" alt="Basketball" src="images/bball court.png"/>';
	}
	if (loc[5] == '1') {
		text += '<img class="iconClass" title="Open Field" alt="Open Field" src="images/field.png"/>';
	}
	if (loc[6] == '1') {
		text += '<img class="iconClass" title="Baseball Diamond" alt="Baseball Diamond" src="images/baseball.png"/>';
	}

	return text;

}

function getOngoingEvents(loc, gamesList) {
	var text = "<b>Ongoing Events:</b>";
	if (gamesList) {
		for (j = 0; j < gamesList.length; j++) {
			// games = [gamesList[i].e_id, gamesList[i].e_sport];
			text += "<li><a title=\"Click for Event Details\" href=\"#\" onClick=\"getEventData(" + gamesList[j].e_id + ")\">"
					+ gamesList[j].e_sport + "game" + gamesList[j].e_id + "</a></li>";
		}
		text+="</ul>"
	}
	else{
		/*text += "<a title=\"Click for Event Details\" href=\"#\" onClick=\"getEventData(1)\">"
		+"game</a><br/>";
		*/
		text += "<li>"
			+"No Games Available</li>";
	}
	return text;
}

function getCreateText() {
	var text="<a style=\"font-weight:bold;\" title=\"Click to Create a New Event\" href=\"#\" onClick=\"createMyEvent()\">Create New Event</a>";
//	var text = "<div align=\"center\"><p><button onClick=\"createMyEvent()\">Create New Event</button></p></div>";
	return text;
}
function getEventDetails(eventData) {
	var detailDivContents = document.getElementById('event-details').innerHTML;
	var newHTML = '<h2>Event Details</h2>' +
	'<b>'+eventData[0].f_name + '</b><br/>'+
	'<b>Sport</b>: ' + eventData[0].e_sport + '<br/>'+
	'<b>Skill Level</b>: ' + eventData[0].e_skill + '<br/>'+
	'<b>Start Time</b>: ' + eventData[0].e_timestart + '<br/>'+
	'<b>End Time</b>: ' + eventData[0].e_timestop+
	'<hr/>' +
	'<div id=\"eventTitle\" title=\"'+eventData[0].e_id+'\"</div>'
	+ 'Would you like to join this event?'
	+ '<div>Number of people: <input type=\"text\" maxlength=\"2\" size=\"2\" id=\"join_numppl\" title=\"join_numppl\" /></div>'
	+ '<input type=\"checkbox\" id=\"join_equipment\" class=\"checkbox\">'
	+ '<label class=\"checkboxLabel\">' + '    I have equipment'
	+ '</label>' + '</input>'
	+'<p><button id=\"submitJoin\" onClick=\"joinSportEvent()\">Join Event</button></p>';
//	var newHTML = '<div id="content" >'
//			+ '<h3 id="firstHeading" class="firstHeading">Basketball Game 1</h1>'
//			+ '<div id="bodyContent">' + '<p>Boston Commons</p>'
//			+ '<p>Skill Level: Competitive</p>'
//			+ '   <button id=\"submit\" class=\"button\">'
//			+ '       Join Event' + '   </button>' + '</div>' + '</div>';
	document.getElementById('event-details').innerHTML = newHTML;
}
function joinSportEvent(){
	var eid = document.getElementById('eventTitle').title;
	var enumppl=document.getElementById('join_numppl').value;
	var eequipment = document.getElementById('join_equipment').value;
	joinEvent(eid, enumppl, eequipment)
	alert("Event Updated!");
	//alert(eid+"."+numppl + "." + equipment);
}
function createMyEvent() {

	var newHTML = '<h2>Create Event</h2>' 
		    + '<div id=\"UIWrapper\" style=\"text-align:center;\">'
			+ '<div>'
			+ '<select id=\"sport\" class=\"dropList\">'
			+ '<option value=\"\" selected=\"selected\">Select Sport:</option>'
			+ '<option value=\"basketball\">Basketball</option>'
			+ '<option value=\"baseball\">Baseball</option>'
			+ '<option value=\"soccer\">Soccer</option>'
			+ '<option value=\"ultimate\">Ultimate Frisbee</option>'
			+ '<option value=\"rugby\">Rugby</option>'
			+ '<option value=\"kickball\">Kickball</option>'
			+ '<option value=\"dodgeball\">Dodgeball</option>'
			+ '</select>'
			+ '</div>'
			+ '<div>'
			+ '<select id=\"skill\" class=\"dropList\">'
			+ '<option value=\"\" selected=\"selected\">Select Skill Level:</option>'
			+ '<option value=\"anything_goes\">Anything goes</option>'
			+ '<option value=\"casual\">Casual</option>'
			+ '<option value=\"competitive\">Competitive</option>'
			+ '</select>'
			+ '</div>'
			+ '<div>'
			+ '<select id=\"duration\" class=\"dropList\">'
			+ '<option value=\"\" selected=\"selected\">Select Duration:</option>'
			+ '<option value=\"30\">30 min</option>'
			+ '<option value=\"60\">60 min</option>'
			+ '<option value=\"90\">1hr 30 min</option>'
			+ '<option value=\"120\">2hr</option>'
			+ '<option value=\"150\">2hr 30min</option>'
			+ '<option value=\"180\">3hr</option>' + '</select>' + '</div>'
			+ '<input type=\"checkbox\" id=\"checkbox\" class=\"checkbox\">'
			+ '<label class=\"checkboxLabel\">' + '    I have equipment'
			+ '</label>' + '</input>' + '<div>'
			+ '<button id=\"submit\" onClick=\"createSportEvent();\">Create Event'
			+ '</div>' + '</div>';
	document.getElementById('event-details').innerHTML = newHTML;
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays(markersArray, map) {
	if (markersArray) {
		for (i in markersArray) {
			markersArray[i].setMap(null);
		}
	}
}

// Shows any overlays currently in the array
function showOverlays(markersArray, map) {
	if (markersArray) {
		for (i in markersArray) {
			markersArray[i].setMap(map);
		}
	}
}

function setMarkers(map, locations) {
	// Add markers to the map

	// Marker sizes are expressed as a Size of X,Y
	// where the origin of the image (0,0) is located
	// in the top left of the image.

	// Origins, anchor positions and coordinates of the marker
	// increase in the X direction to the right and in
	// the Y direction down.
	var image = new google.maps.MarkerImage('images/beachflag.png',
	// This marker is 20 pixels wide by 32 pixels tall.
	new google.maps.Size(20, 32),
	// The origin for this image is 0,0.
	new google.maps.Point(0, 0),
	// The anchor for this image is the base of the flagpole at 0,32.
	new google.maps.Point(0, 32));
	var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
	// The shadow image is larger in the horizontal dimension
	// while the position and offset are the same as for the main image.
	new google.maps.Size(37, 32), new google.maps.Point(0, 0),
			new google.maps.Point(0, 32));
	// Shapes define the clickable region of the icon.
	// The type defines an HTML <area> element 'poly' which
	// traces out a polygon as a series of X,Y points. The final
	// coordinate closes the poly by connecting to the first
	// coordinate.
	var shape = {
		coord : [ 1, 1, 1, 20, 18, 20, 18, 1 ],
		type : 'poly'
	};

	var latlngbounds = new google.maps.LatLngBounds();
	for ( var i = 0; i < locations.length; i++) {
		var loc = locations[i];
		var myLatLng = new google.maps.LatLng(loc[1], loc[2]);

		var popupContent = '<div id="content" >'
				+ '<h3 id="firstHeading" class="firstHeading">' + loc[0]
				+ '</h1><hr/>' + '<div id="bodyContent">' + getCapability(loc)
				+ '<hr/><div>' + getOngoingEvents(loc) + '</div><hr/>' + getCreateText() +
				// '<p><input type=\"button\" onClick=\"createMyEvent()\">Create
				// New Event</input></p>' +
				'</div>' + '</div>';

		var marker = new google.maps.Marker({
			position : myLatLng,
			map : map,
			// shadow: shadow,
			// icon: image,
			shape : shape,
			title : loc[0]
		});
		markerArray.push(marker);
		createInfoWindow(map, marker, popupContent);
		latlngbounds.extend(myLatLng);
	}

	map.fitBounds(latlngbounds);
}
function clearMarkers(map) {
	if (markerArray) {
		for (i in markerArray) {
			markerArray[i].setMap(null);
		}
		markerArray.length = 0;
		latlngbounds=new google.maps.LatLngBounds();
	}
}
function setMarker(map, field, gamesList) {

	// [fieldList[i].f_id, fieldList[i].f_lat, fieldList[i].f_long];

	// Add markers to the map

	// Marker sizes are expressed as a Size of X,Y
	// where the origin of the image (0,0) is located
	// in the top left of the image.

	// Shapes define the clickable region of the icon.
	// The type defines an HTML <area> element 'poly' which
	// traces out a polygon as a series of X,Y points. The final
	// coordinate closes the poly by connecting to the first
	// coordinate.
	var shape = {
		coord : [ 1, 1, 1, 20, 18, 20, 18, 1 ],
		type : 'poly'
	};
	var myLatLng = new google.maps.LatLng(field[2], field[3]);
	//var latlngbounds = new google.maps.LatLngBounds();

	// var myLatLng = new google.maps.LatLng(loc[1], loc[2]);
	var popupContent = '<div id="content" title='+field[0]+'>'
			+ '<h3 id="firstHeading" class="firstHeading">' + field[1]
			+ '</h1>' + '<div id="bodyContent">' + getCapability(field) 
			+ '<div>' + getOngoingEvents(field, gamesList) + '</div><hr/>'
			+ getCreateText() + '</div>' + '</div>';
//alert(field[2] + ',' + field[3]);
	var marker = new google.maps.Marker({
		position : myLatLng,
		map : map,
		// shadow: shadow,
		// icon: image,
		shape : shape,
		title : field[1]
	});
	markerArray.push(marker);
	createInfoWindow(map, marker, popupContent);
	 
	latlngbounds.extend(myLatLng);
	map.fitBounds(latlngbounds);
}

var infoWindow = new google.maps.InfoWindow();
function createInfoWindow(map, marker, popupContent) {
	google.maps.event.addListener(marker, 'click', function() {
		infoWindow.setContent(popupContent);
		infoWindow.open(map, this);
	});
}
